package krow.dev.gunpobus;

import krow.dev.gunpobus.Constants.Invoke;
import krow.dev.gunpobus.Constants.Value;
import krow.dev.gunpobus.control.database.DataController;
import krow.dev.gunpobus.control.http.HtmlResponseListener;
import krow.dev.gunpobus.control.http.RequestManager;
import krow.dev.gunpobus.control.parser.ScheduleParser;
import krow.dev.gunpobus.model.ScheduleItem;
import krow.dev.gunpobus.view.RetryViewWrapper;
import krow.dev.gunpobus.view.adapter.ScheduleListAdapter;
import krow.dev.gunpobus.view.dialog.LoadDialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.VolleyError;

public class ScheduleActivity extends Activity implements OnClickListener{

	private ScheduleListAdapter mScheduleListAdapter;
	private ListView mScheduleListView;
	private TextView mTitleView;
	private View mFavoriteView;
	private View mRefreshView;
	private ViewGroup mListLayout;
	private RetryViewWrapper mRetryViewWrapper;
	
	private DataController mDataController;
	private Dialog mDialog;

	private String mStationId;
	private String mStationName;
	private String mStationSerial;
	
	private Request<?> mRequest;
	private Handler mHandler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_schedule);
		
		mDataController = GlobalStore.getInstance().getDataController();
		
		Intent intent = getIntent();
		if(intent != null){
			mStationName = intent.getStringExtra(Invoke.KEY_STATION_NAME);
			mStationId = intent.getStringExtra(Invoke.KEY_STATION_ID);
			mStationSerial = intent.getStringExtra(Invoke.KEY_STATION_SERIAL);
		}
		
		initializeView();
	}
	
	private void initializeView(){
		
		mScheduleListAdapter = new ScheduleListAdapter(getApplicationContext());
		mScheduleListView = (ListView) findViewById(R.id.listview_schedule);
		mScheduleListView.setOnItemClickListener(mItemClickListener);
		mScheduleListView.addFooterView(getLayoutInflater().inflate(R.layout.footer_dummy, null));
		mScheduleListView.setAdapter(mScheduleListAdapter);
		
		mTitleView = (TextView) findViewById(R.id.text_title);
		mTitleView.setText(mStationName);
		
		mFavoriteView = findViewById(R.id.layout_favorite);
		mFavoriteView.setOnClickListener(this);
		
		mRefreshView = findViewById(R.id.layout_refresh);
		mRefreshView.setOnClickListener(this);
		
		if(mDataController.isFavorited(Value.TYPE_FAVORITE_STATION, mStationId)){
			mFavoriteView.setSelected(true);
		}else{
			mFavoriteView.setSelected(false);
		}
		
		mListLayout = (ViewGroup) findViewById(R.id.layout_list);
		
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		
		mRetryViewWrapper = new RetryViewWrapper(getApplicationContext());
		mRetryViewWrapper.setRetryClickListener(mRetryClickListener);
		mListLayout.addView(mRetryViewWrapper.getView(), layoutParams);
		
		findViewById(R.id.layout_title).setOnClickListener(this);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		requestSchedule();
	}
	
	@Override
	protected void onPause() {

		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		if(mRequest != null){
			mRequest.cancel();
		}
		super.onDestroy();
	}
	
	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.scale_in, R.anim.right_out);
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.layout_favorite:
			if(mFavoriteView.isSelected()){
				mFavoriteView.setSelected(false);
				mDataController.deleteFavoriteItem(
						Value.TYPE_FAVORITE_STATION,
						mStationId);
			}else{
				mFavoriteView.setSelected(true);
				mDataController.insertFavoriteItem(
						Value.TYPE_FAVORITE_STATION,
						mStationName,
						mStationId,
						mStationSerial,
						0);
			}
			break;
		case R.id.layout_refresh:
			requestSchedule();
			break;
		case R.id.layout_title:
			finish();
			break;
		}
	}
	
	private void requestSchedule(){
		if(mRetryViewWrapper != null){
			mRetryViewWrapper.setVisibility(View.GONE);
		}
		if(mStationId == null){
			return ;
		}
		
		if(mDialog != null){
			mDialog.dismiss();
		}
		mDialog = new LoadDialog(this);
		mDialog.show();
		
		mRequest = RequestManager.requestArrivalState(mStationId, mResponseListener);
	}
	
	private HtmlResponseListener<ScheduleParser> mResponseListener = new HtmlResponseListener<ScheduleParser>() {

		@Override
		public void onResponse(ScheduleParser response) {
			if(mDialog != null){
				mDialog.dismiss();
			}
			
			mScheduleListAdapter.setScheduleItemList(response.getScheduleItemList());
			mScheduleListAdapter.notifyDataSetChanged();
		}

		@Override
		public void onErrorResponse(VolleyError error) {
			mHandler.postDelayed(mRequestFailureRunnable, 1000);
		}
	};
	
	private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if(view.getTag() == null){
				return ;
			}

			ScheduleItem scheduleItem = (ScheduleItem) view.getTag();
			String estimatedStation = scheduleItem.getEstimatedStation();
			if(estimatedStation == null || estimatedStation.trim().length() == 0){
				return ;
			}
			
			Intent intent = new Intent(ScheduleActivity.this, NodeActivity.class);
			intent.putExtra(Invoke.KEY_ROUTE_NAME, scheduleItem.getName());
			intent.putExtra(Invoke.KEY_ROUTE_ID, scheduleItem.getId());
			intent.putExtra(Invoke.KEY_ROUTE_TYPE, scheduleItem.getType());
			startActivity(intent);
			overridePendingTransition(R.anim.right_in, R.anim.scale_out);
		}
	};
	
	private Runnable mRequestFailureRunnable = new Runnable() {
		
		@Override
		public void run() {
			if (mDialog != null) {
				mDialog.dismiss();
			}
			mScheduleListAdapter.clear();
			mScheduleListAdapter.notifyDataSetChanged();
			mRetryViewWrapper.setVisibility(View.VISIBLE);
		}
	};
	
	private View.OnClickListener mRetryClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View view) {
			requestSchedule();
		}
	};
}
